<?php

/**
 * A simple extension to dropdown field, pre-configured to list currencies.
 * It will default to the currency of the current visitor.
 *
 * @package forms
 * @subpackage fields-relational
 */
class CurrencyDropdownField extends DropdownField {

	/**
	 * Should we default the dropdown to the region determined from the user's locale?
	 * @var bool
	 */
	private static $default_to_locale = true;

	protected $extraClasses = array(
		'selectpicker' => 'selectpicker'
	);

	/**
	 * Get the locale of the Member, or if we're not logged in or don't have a locale, use the default one
	 * @return string
	 */
	protected function locale() {
		return i18n::get_locale();
	}

	public function __construct($name, $title = null, $source = null, $value = "", $form=null) {
		if(!is_array($source)) {
			// Get a list of countries from Zend
			$source = Zend_Locale::getTranslationList('nametocurrency', $this->locale(), 2);

			// We want them ordered by display name, not currency code

			// PHP 5.3 has an extension that sorts UTF-8 strings correctly
			if (class_exists('Collator') && ($collator = Collator::create($this->locale()))) {
				$collator->asort($source);
			}
			// Otherwise just put up with them being weirdly ordered for now
			else {
				asort($source);
			}
		}

		parent::__construct($name, ($title===null) ? $name : $title, $source, $value, $form);
	}

	public function Field($properties = array()) {
		$source = $this->getSource();

		if (!$this->value || !isset($source[$this->value])) {
			if ($this->config()->default_to_locale && $this->locale()) {
				require_once 'Zend/Currency.php';
				$currency = new Zend_Currency(null, $this->locale());
				$this->value = $currency->getShortName();
			}
		}

		if (!$this->value || !isset($source[$this->value])) {
			$this->value = SiteCurrencyConfig::current_site_currency();
		}

		return parent::Field();
	}
	
	function getAttributes() {
        return array_merge(
            parent::getAttributes(), array(
                'data-live-search' => 'true'
            )
        );
    }
	
	function Type(){
		return 'currencydropdown dropdown';
	}
}
